package com.loveazure.bll;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Set;

import org.apache.log4j.Logger;

import com.loveazure.bll.algorithm.WordItem;
import com.loveazure.eo.Dict;
import com.loveazure.eo.UserCourse;
import com.loveazure.eo.WordLearned;
import com.loveazure.util.MyLogger;

public class WordProvider {

	private Handler handler;
	private int line;
	private Logger logger;
	private BufferedReader reader;

	public WordProvider() {
		this.logger = MyLogger.getLogger();
		this.handler = Handler.getInstance();

		// handler.getOper().refreshWordTimes();

		UserCourse userCourse = handler.getUserCourse();
		if (userCourse == null) {
			logger.error("current user course can not be null");
			return;
		}

		Set<WordLearned> set = userCourse.getWordLearned();
		line = set.size();
		try {
			File file = new File("user" + File.separatorChar
					+ handler.getUser().getName(), userCourse.getCourse()
					.getFileName());
			System.out.println(file.getPath());
			reader = new BufferedReader(new FileReader(file));
			for (int i = 0; i < line; i++) {
				reader.readLine();
			}
		} catch (Exception e) {
			logger.error("can not read course file.");
			
		}
	}

	public WordItem[] getAllLearnedWords() {

		Set<WordLearned> wordLearnedSet = handler.getUserCourse()
				.getWordLearned();

		if (wordLearnedSet == null || wordLearnedSet.size() == 0) {
			return null;
		}

		WordItem[] items = new WordItem[wordLearnedSet.size()];
		int i = 0;

		for (WordLearned w : wordLearnedSet) {
			items[i] = new WordItem(w);
			i++;
		}

		return items;
	}

	public WordItem getNewWord() {
		String word;
		WordLearned wordLearned;

		try {
			word = reader.readLine();

			if (word == null) {
				return null;
			}

			// word = word.substring(0, word.indexOf("=")).trim();
			word = word.trim();
			Dict dict = handler.getOper().getDictByWord(word);

			if (dict == null) {
				logger.info("the word '" + word + "' might invalid");
				return getNewWord();
			}

			wordLearned = new WordLearned();
			wordLearned.setTimes(1);
			wordLearned.setDict(dict);
			wordLearned.setUserCourse(Handler.getInstance().getUserCourse());

			handler.getProgress().increaseNumber();
			return new WordItem(wordLearned);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
}
